package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.example.demo.entity.Comment;
import com.example.demo.entity.Post;
import com.example.demo.mapper.CommentMapper;
import com.example.demo.mapper.PostMapper;
import com.example.demo.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Autowired
    private CommentMapper commentMapper;
    private PostMapper postMapper;

    @Override
    public Post getPostDetail(String postId) {
        Post post = getById(postId);
        if (post != null) {
            List<Comment> comments = commentMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Comment>().eq("post_id", postId));
            post.setComments(comments);
        }
        return post;
    }

    @Override
    public void createPost(Post post) {
        post.setCreateTime(new Date());
        post.setLikes(0);
        post.setIsLiked(false);
        save(post);
        postMapper.insertpost(post);
    }

    @Transactional
    @Override
    public Post likePost(String postId, boolean isLiked) {
        Post post = getById(postId);
        if (post != null) {
            if (isLiked) {
                post.setLikes(post.getLikes() + 1);
            } else {
                post.setLikes(post.getLikes() - 1);
            }
            post.setIsLiked(isLiked);
            updateById(post);
        }
        return post;
    }

    @Transactional
    @Override
    public Post submitComment(String postId, String userId, String content) {
        Comment comment = new Comment();
        comment.setPostId(postId);
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setCreateTime(new Date());
        commentMapper.insert(comment);

        return getPostDetail(postId);
    }
//    @Transactional
    @Override
    public List<Post> getHotPosts() {
        // 按照点赞数降序排序，取前 10 条帖子作为热门帖子
        return this.lambdaQuery()
                .orderByDesc(Post::getLikes)
                .last("LIMIT 10")
                .list();
    }
}